<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/adminHome.css" rel="stylesheet" type="text/css"/>
<link href="css/usersHome.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
    <script>
  function changeRemainingHours(span, input, projectscnt, consultanciescnt, workingHours) {
  
	var totalHours = 0;
	
	for (i = 0; i < projectscnt; i++) {
		inputName = "projectsHoursInput" + i;
		hora = parseInt(document.getElementById(inputName).value);
		totalHours = totalHours + hora;
	}
	for (i = 0; i < consultanciescnt; i++) {
		inputName = "consultanciesHoursInput" + i;
		hora = parseInt(document.getElementById(inputName).value);
		totalHours = totalHours + hora;
	}
	
	
	remainingHours = workingHours - totalHours;
	
	if (remainingHours < 0) {
		span.className = "bigRedText";
		document.getElementById('saveButton').disabled = true;
	}else{
		document.getElementById('saveButton').disabled = false;
		span.className = "bigGreenText";
	}
	span.firstChild.nodeValue = remainingHours;
  }
  
  function changeLastMonthRemainingHours(span, input, projectscnt, consultanciescnt, workingHours) {
  
	var totalHours = 0;
	
	for (i = 0; i < projectscnt; i++) {
		inputName = "projectsLastMonthHoursInput" + i;
		hora = parseInt(document.getElementById(inputName).value);
		totalHours = totalHours + hora;
	}
	for (i = 0; i < consultanciescnt; i++) {
		inputName = "consultanciesLastMonthHoursInput" + i;
		hora = parseInt(document.getElementById(inputName).value);
		totalHours = totalHours + hora;
	}
	
	
	remainingHours = workingHours - totalHours;
	
	if (remainingHours < 0) {
		span.className = "bigRedText";
		document.getElementById('lastMonthSaveButton').disabled = true;
	}else{
		document.getElementById('lastMonthSaveButton').disabled = false;
		span.className = "bigGreenText";
	}
	span.firstChild.nodeValue = remainingHours;

  }
  
  function showCharge(){ 
	document.getElementById('charge').style.display = "block"; 
	document.getElementById('chargeButton').style.display = "none"; 
	document.getElementById('chargeMenu').style.display = "none"; 
  }
  
    function showLastMonthCharge(){ 
	document.getElementById('lastMonthCharge').style.display = "block"; 
	document.getElementById('lastMonthChargeButton').style.display = "none"; 
	document.getElementById('chargeMenu').style.display = "none"; 
  }
  
  function hideCharge(){ 
	document.getElementById('charge').style.display = "none"; 
	document.getElementById('chargeButton').style.display = "block"; 
	document.getElementById('chargeMenu').style.display = "block"; 
  }
  
  function hideLastMonthCharge(){ 
	document.getElementById('lastMonthCharge').style.display = "none"; 
	document.getElementById('lastMonthChargeButton').style.display = "block";
	document.getElementById('chargeMenu').style.display = "block";  
  }
  
  function showConfirmation(){
  	confirmation = confirm("¿Desea cargar los datos?")
	if (confirmation !="0"){
		document.forms["hours"].submit();
	}
  }
  
    function showLastMonthChargeConfirmation(){
  	confirmation = confirm("¿Desea cargar los datos?")
	if (confirmation !="0"){
		document.forms["lastMonthHours"].submit();
	}
  }
  
  function hideConfirmation(){
  	document.getElementById('saveConfirmation').style.display = "none"; 
	document.getElementById('charge').style.display = "block"; 

  }
  </script>
<script>
function hideDiv(div) {
	document.getElementById(div).style.display = "none";
	document.getElementById('menu').style.display = "block";
}
function showDiv(div) {
	document.getElementById(div).style.display = "block";
	document.getElementById('menu').style.display = "none";
}
</script>

</head>

<body>
 
<?php
	
	include_once('frontend/header.php');
	include_once('functions/getDateInformation.php');
	$date = date("d-m-Y");
	$month = getMonth($date);
	$monthName = getMonthName($month);
	$prevMonth = getPrevMonth($date);
	$prevMonthName = getMonthName($prevMonth);
?>
	
    
<div class="container">
	<div class="menu" id="menu">
       <br /><br /> 
       <input type="button" value="Dar de alta un nuevo proyecto"  onclick="showDiv('projectCharge')" /><br />
       <input type="button" value="Dar de alta una nueva consultoria" onclick="showDiv('consultancyCharge')"  /><br /><br />
       <input type="button" value="Dar de alta un nuevo recurso" onclick="showDiv('resourceCharge')"  /><br />
       <input type="button" value="Editar un recurso" onclick="showDiv('resourceModify')"  /><br /><br />
       <input type="button" value="Ver estado de usuarios" onclick="showDiv('resourcesState')"  /><br /><br />
       <input type="button" value="Ver costos de los proyectos de <?php echo $prevMonthName ?>" onclick="showDiv('projectsCosts')"  /><br />
       <br /><br /><br />
   </div>

    <div>
        <div class="projectCharge" id="projectCharge" style="display:none">
     <a class="boldText">Nuevo proyecto:</a><br /><br />     
    <form action="adminsCharge.php" method="post">
        <table width="300" border="0" cellspacing="1" cellpadding="9">
        <tr class="row">
        <td>Codigo del proyecto:</td>
        <td><input name="code" type="text" /></td>
        </tr>
        <tr class="row">
        <td>Nombre del proyecto:</td>
        <td><input name="name" type="text" /></td>
        </tr>
        </table>
        <input type="hidden" name="user" value="<?php echo $user?>" />
        <input name="project" type="hidden" value="" />
  
    	<br />
   		<input type="submit" value="Crear" /><input type="button" value="Cancelar" onclick="hideDiv('projectCharge')" /> 
    </form>
  </div>
        
        <div class="consultancyCharge" id="consultancyCharge" style="display:none">
         <a class="boldText">Nueva consultoria:</a><br /><br /> 
        <form action="adminsCharge.php" method="post">     
            <table width="300" border="0" cellspacing="1" cellpadding="9">
            <tr class="row">
            <td>Codigo de la consultoria:</td>
            <td><input name="code" type="text" /></td>
            </tr>
            <tr class="row">
            <td>Nombre de la consultoria:</td>
            <td><input name="name" type="text" /></td>
            </tr>
            </table>
            <input type="hidden" name="user" value="<?php echo $user?>" />
            <input name="consultancy" type="hidden" value="" />
        
   			<br />       
        	<input type="submit" value="Crear" /><input type="button" value="Cancelar" onclick="hideDiv('consultancyCharge')" /> 
        </form>
    </div>
    
    <div class="resourceCharge" id="resourceCharge" style="display:none">
        <a class="boldText">Nuevo recurso:</a><br /><br /> 
        <form action="adminsCharge.php" method="post">     
            <table width="300" border="0" cellspacing="1" cellpadding="9">
            <tr class="row">
            <td>Nombre:</td>
            <td><input name="name" type="text" /></td>
            </tr>
            <tr class="row">
            <td>Apellido:</td>
            <td><input name="surname" type="text" /></td>
            </tr>
            <tr class="row">
            <td>Dni:</td>
            <td><input name="dni" type="text" /></td>
            </tr>
            <tr class="row">
            <td>Correo Electronico:</td>
            <td><input name="mail" type="text" /></td>
            </tr>
            <tr class="row">
            <td>Sueldo:</td>
            <td><input name="salary" type="text" /></td>
            </tr>
            </table>
            <input type="hidden" name="user" value="<?php echo $user?>" />
            <input name="resource" type="hidden" value="" />
        
   			<br />       
        	<input type="submit" value="Crear" /><input type="button" value="Cancelar" onclick="hideDiv('resourceCharge')" /> 
        </form>
    </div>
      <div class="resourceModify" id="resourceModify" style="display:none">
         <a class="boldText">Modificar recurso:</a><br /><br /> 
        <?php		
			$query = "SELECT name, surname, dni, mail, salary FROM users WHERE user = 'alan33209812'"; 
			$result = mysqli_query($connection, $query); 
			$row = mysqli_fetch_array($result);
			$name = $row['name'];
			$surname = $row['surname'];
			$dni = $row['dni'];
			$mail = $row['mail'];
			$salary = $row['salary'];
        ?> 
        
        <form action="adminsCharge.php" method="post">     
            <table width="300" border="0" cellspacing="1" cellpadding="9">
            <tr class="row">
            <td>Nombre:</td>
            <td><input name="name" type="text" value="<?php echo $name?>" /></td>
            </tr>
            <tr class="row">
            <td>Apellido:</td>
            <td><input name="surname" type="text" value="<?php echo $surname?>" /></td>
            </tr>
            <tr class="row">
            <td>Dni:</td>
            <td><input name="dni" type="text" value="<?php echo $dni?>" /></td>
            </tr>
            <tr class="row">
            <td>Correo Electronico:</td>
            <td><input name="mail" type="text" value="<?php echo $mail?>" /></td>
            </tr>
            <tr class="row">
            <td>Sueldo:</td>
            <td><input name="salary" type="text" value="<?php echo $salary?>" /></td>
            </tr>
            </table>
            <input type="hidden" name="user" value="<?php echo $user?>" />
            <input name="modifyResource" type="hidden" value="" />
        
   			<br />       
        	<input type="submit" value="Modificar" /><input type="button" value="Cancelar" onclick="hideDiv('resourceModify')" /> 
        </form>
    	</div>
        <div class="resourcesState" id="resourcesState" style="display:none">
        <a class="boldText">Usuarios que no han actualizado la carga de horarios de </a><?php echo "<a class='blueText'>$prevMonthName</a>" ?>:<br /><br /> 
                <table width="200" border="0" cellspacing="1" cellpadding="9">
                <tr class="row boldText">
                <td>Nombre</td>
           		<td>Apellido</td>
                <td>DNI</td>
           		</tr>
				<?php		
					$query = "SELECT name, surname, dni FROM users WHERE updated = '0'"; 
					$result = mysqli_query($connection, $query); 
					$i = 0;
					while ($row = mysqli_fetch_array($result)) {
						echo "<tr class='row'><td>$row[name]</td>";
						echo "<td>$row[surname]</td>";
						echo "<td>$row[dni]</td></tr>";
						$i++;      
					}	
        		?>    
        	 	</table><br />
                <input type="button" value="Volver" onclick="hideDiv('resourcesState')" /> 
    	</div>
        <div class="projectsCosts" id="projectsCosts" style="display:none">
        <a class="boldText">Costos de los proyectos de </a><?php echo "<a class='blueText'>$prevMonthName</a>" ?>:<br /><br /> 
                <table width="450" border="0" cellspacing="1" cellpadding="9" align="center">
                <tr class="row boldText">
                <td>Codigo del proyecto</td>
                <td>Nombre</td>
           		<td>Costo</td> 
                <td>Cantidad de participantes</td>
           		</tr>
				<?php		
					include_once('functions/costCalculation.php');
					list($projects, $projectsNames, $consultancies, $consultanciesNames, $projectsCosts, $consultanciesCosts, $projectMembers, $consultancyMembers) = calculateCostPerProject($date);
					$cnt = 0;
					foreach ($projects as $project){
						echo "<tr class='row'>";
						echo "<td>$project</td><td>$projectsNames[$cnt]</td><td>$ $projectsCosts[$project]</td><td>$projectMembers[$project]</td>";
						echo "</tr>";
						$cnt++;
					}
        		?>    
        	 	</table><br />
                 <table width="450" border="0" cellspacing="1" cellpadding="9" align="center">
                <tr class="row boldText">
                <td>Codigo de la consultoria</td>
                <td>Nombre</td>
           		<td>Costo</td>
                <td>Cantidad de participantes</td> 
           		</tr>
                <?php
					$cnt = 0;		
					foreach ($consultancies as $consultancy){
						echo "<tr class='row'>";
						echo "<td>$consultancy</td><td>$consultanciesNames[$cnt]</td><td>$ $consultanciesCosts[$consultancy]<td>$consultancyMembers[$consultancy]</td></td>";
						echo "</tr>";
						$cnt++;
					}
        		?>   
                </table><br />
                <input type="button" value="Volver" onclick="hideDiv('projectsCosts')" /> 
    	</div>
   <div>
 	       <br /><br /> 
     
   
   	  <?php
		 include_once("functions/getDateInformation.php");
		 include_once("functions/checkUserState.php");
		 $date = date("d-m-Y"); 
		 $beginingCharge = getBeginingDate($date);
		 $lastMonthEndingDay = getLastMonthEndingDay($date);
		 $lastMonthLastChargeDay = getLastMonthLastChargeDay($user, $date);
		 $state = getState($user);
	  ?>
    
       <table width="500" border="0" cellspacing="1" cellpadding="9">
          <tr class="row">
            <td>Última carga de datos:</td>
            <td>
			<?php
			   include_once("functions/getDateInformation.php");
			   $lastCharge = getLastChargeDate($user);
			   echo $lastCharge;	   
			?>
			</td>
          </tr>
          <tr class="row">
            <td>Fecha de cierre de liquidación de horas:</td>
            <td>
			<?php 
				
				include_once("functions/getDateInformation.php");
				echo getEndingDate($date);			
				
			?>
            </td>
          </tr>
          <tr class="row">
            <td>Fecha actual</td>
            <td>
			<?php 
				echo $date;
			?>
            </td>
          </tr>
     
      </table>
    
        <br /><br />
         <div id="chargeMenu">
		<?php 
		if (strcmp($state, "not-updated") == 0) {
					echo "<a class='redText'>ATENCION! La carga pasada de horas del mes pasado se encuentra desactualizada</a><br />";
					echo '<input type="button" value="Cargar horas del mes pasado" onclick="showLastMonthCharge()" id="lastMonthChargeButton" /><br /><br />';
				}
			if ( strtotime($lastCharge) <  strtotime($date) || $lastCharge == "no hay cargas registradas") { 
        		echo "<a class='redText'>La carga de horas se encuentra desactualizada</a><br />";
				echo '<input type="button" value="Cargar Horas" onclick="showCharge()" id="chargeButton" />';
				
			}else{
				echo "<a class='greenText'>La carga de horas se encuentra actualizada<a/>";
			}
		?>
        </div>
        
      <br /><br />
      <div class="charge" id="charge">
      <?php 
	  if (strtotime($lastCharge) <= strtotime($beginingCharge) || strcmp($lastCharge, "no hay cargas registradas") == 0) {
	  	$startRange = $beginingCharge;
		$endingRange = $date;	
	  }else{
	  	$startRange = $lastCharge;
	  	$endingRange = $date;
	  }
	  echo "Carga de horarios desde el <a class='bigBlueText'>$startRange</a> al <a class='bigBlueText'>$endingRange</a><br /><br />";
	  $workingDays = count(getDiasHabiles($startRange, $endingRange, $diasferiados = array()));
	  $workingHours = $workingDays * 8;
	  ?>
      
      <form action="dataCharge.php" method="post" id="hours" name="hours">
    	

      <div id="projects" style="display:inline-block;float:left;">
          <table width="300" border="0" cellspacing="1" cellpadding="9"> 
          <tr class="row boldText">
                <td>Proyectos</td>
                <td>Cantidad de horas</td>
              </tr>
                <?php
				$spanId = "remainingDays";
				
                $query = "SELECT name FROM projects"; 
                $result = mysqli_query($connection, $query); 
				$totalProjects = mysqli_num_rows($result);
				
				$query2 = "SELECT name FROM consultancies"; 
                $result2 = mysqli_query($connection, $query2); 
				$totalConsultancies =mysqli_num_rows($result2);
				
				$projectscnt = 0;
				$consultanciescnt = 0;
								
				
                while ($row = mysqli_fetch_array($result)) {
				
                    echo "<tr class='row'><td>$row[name]</td>";
                    echo "<td><input onChange='changeRemainingHours(".$spanId.", this,".$totalProjects.",".$totalConsultancies.",".$workingHours.")' type='text' class='hoursInput' maxlength='3' name='projects[$row[name]]' value='0' id='projectsHoursInput$projectscnt' onclick='this.select()'/>&nbsp;hs.</td></tr>";
                     $projectscnt++;
                }	
                ?>            
          </table>
      </div>
      <div id="consultancies" style="display:inline-block">
          <table width="300" border="0" cellspacing="1" cellpadding="9">   
          <tr class="row boldText">
                <td>Consultorias</td>
                <td>Cantidad de horas</td>
          </tr>
          <?php
             
               
				while ($row = mysqli_fetch_array($result2)) {
                    echo "<tr class='row'><td>$row[name]</td>";
                    echo "<td><input onChange='changeRemainingHours(".$spanId.", this,".$totalProjects.",".$totalConsultancies.",".$workingHours.")' type='text' class='hoursInput' maxlength='3' name='consultancies[$row[name]]' value='0' id='consultanciesHoursInput$consultanciescnt' onclick='this.select()' />&nbsp;hs.</td></tr>";
               		$consultanciescnt++;			           
                }	
           ?>
             
          </table> 
           <br />
           </div>
          <?php 
		 echo '<center><a class="bigBlueText">Dias habiles del periodo: </a><a class="bigGreenText">'.$workingDays.' &nbsp;&nbsp;&nbsp;  </a><a class="bigBlueText">Horas restantes: </a><span id="remainingDays" class="bigGreenText">' . $workingHours .  '</span></center>';
		  ?>	
          <br />
          <br />
          <input type="hidden" name="date" value="<?php echo $date?>" />
          <input type="hidden" name="user" value="<?php echo $user?>" />
          <input type="button" value="Guardar" id='saveButton' onclick="showConfirmation()"/><input type="button" value="Cancelar" onclick="hideCharge()"/>
        </form>
    
       </div>
       
       <div class="lastMonthCharge" id="lastMonthCharge">
      <?php echo "Carga de horarios desde el <a class='bigBlueText'>$lastMonthLastChargeDay</a> al <a class='bigBlueText'>$lastMonthEndingDay</a><br /><br />";
	  $lastMonthWorkingDays = count(getDiasHabiles($lastMonthLastChargeDay, $lastMonthEndingDay, $diasferiados = array()));
	  $lastMonthWorkingHours = $lastMonthWorkingDays * 8;
	  ?>
      <form action="dataCharge.php" method="post" id="hours" name="lastMonthHours">
      
      <div id="projects" style="display:inline-block;float:left;">
          <table width="300" border="0" cellspacing="1" cellpadding="9"> 
          <tr class="row boldText">
                <td>Proyectos</td>
                <td>Cantidad de horas</td>
              </tr>
                <?php
				$spanId = "lastMonthRemainingDays";
				
                $query = "SELECT name FROM projects"; 
                $result = mysqli_query($connection, $query); 
				$totalProjects = mysqli_num_rows($result);
				
				$query2 = "SELECT name FROM consultancies"; 
                $result2 = mysqli_query($connection, $query2); 
				$totalConsultancies =mysqli_num_rows($result2);
				
				$projectscnt = 0;
				$consultanciescnt = 0;
				
                while ($row = mysqli_fetch_array($result)) {
                    echo "<tr class='row'><td>$row[name]</td>";
                    echo "<td><input onChange='changeLastMonthRemainingHours(".$spanId.", this,".$totalProjects.",".$totalConsultancies.",".$lastMonthWorkingHours.")' type='text' class='hoursInput' maxlength='3' name='projects[$row[name]]' value='0' id='projectsLastMonthHoursInput$projectscnt' onclick='this.select()'/>&nbsp;hs.</td></tr>";
                    $projectscnt++;      
                }	
                ?>            
          </table>
      </div>
      <div id="consultancies" style="display:inline-block">
          <table width="300" border="0" cellspacing="1" cellpadding="9">   
          <tr class="row boldText">
                <td>Consultorias</td>
                <td>Cantidad de horas</td>
          </tr>
          <?php
                $query = "SELECT name FROM consultancies"; 
                $result = mysqli_query($connection, $query); 
                $i = 0;
                while ($row = mysqli_fetch_array($result)) {
                    echo "<tr class='row'><td>$row[name]</td>";
                    echo "<td><input onChange='changeLastMonthRemainingHours(".$spanId.", this,".$totalProjects.",".$totalConsultancies.",".$lastMonthWorkingHours.")' type='text' class='hoursInput' maxlength='3' name='consultancies[$row[name]]' value='0' id='consultanciesLastMonthHoursInput$consultanciescnt' onclick='this.select()'/>&nbsp;hs.</td></tr>";
                    $consultanciescnt++;           
                }	
           ?>
             
          </table> 
          <br />
           </div>
          <?php 
		  echo '<center><a class="bigBlueText">Dias habiles del periodo: </a><a class="bigGreenText">'.$lastMonthWorkingDays.' &nbsp;&nbsp;&nbsp;  <a class="bigBlueText">Horas restantes: </a><span id="lastMonthRemainingDays" class="bigGreenText">' . $lastMonthWorkingHours .  '</span>';
		  /*document.getElementById('pepe').firstChild.nodeVal ue = 'adio
var mensaje= document.getElementById("mensaje").innerHTML*/
		  ?>	
          <br />
          <br />
          <input type="hidden" name="date" value="<?php echo $lastMonthEndingDay ?>" />
          <input type="hidden" name="user" value="<?php echo $user ?>" />
          <input type="button" value="Guardar" id= "lastMonthSaveButton" onclick="showLastMonthChargeConfirmation()"/><input type="button" value="Cancelar" onclick="hideLastMonthCharge()"/>
        </form>
   
       </div>
   
</div>
    

	
</body>
</html>
